<script setup lang="ts">
  import { ref, toRefs, watch } from 'vue'
  import { ElMessage, FormInstance } from 'element-plus'
  import useService from './useService'
  import { checkNum, keepPartInteger } from '@/utils/validate'
  import HButton from '@/components/common/button/HButton.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import useFormValidateService from '@/services/common/formValidate/useFormValidate'

  const props = defineProps({
    oldFactorySettlementPrice: {
      type: String,
      required: true,
    },
    oldNetworkSettlementPrice: {
      type: String,
      required: true,
    },
    orderId: {
      type: String,
      required: true,
    },
    modelValue: Boolean,
  })

  const emits = defineEmits<{
    (e: 'update-list'): void
    (e: 'update:modelValue', value: boolean): void
  }>()

  /**
   * 使用表单验证服务
   */
  const { handleFormValidate, resetFormValidateResult, formValidateResult } =
    useFormValidateService(['factorySettlementPrice'])

  // 使用服务
  const { form, updateLoading, update } = useService([props.orderId])

  // 解构prop
  const { oldNetworkSettlementPrice, oldFactorySettlementPrice } = toRefs(props)

  // 弹窗的显示状态
  const visible = ref(false)

  /**
   * 关闭弹窗
   */
  const onClose = () => {
    visible.value = false
    form.value.factorySettlementPrice = '0'
    form.value.factorySettlementPrice = '0'
    resetFormValidateResult()
    emits('update:modelValue', visible.value)
  }

  // 表单组件实例
  const formRef = ref<FormInstance>()

  /**
   * 保存按钮点击事件
   */
  const onSaveClick = async () => {
    if (formRef.value) {
      try {
        formRef.value.validate()
        const res = await update()
        ElMessage({
          type: res.success ? 'success' : 'error',
          message: res.message,
        })
        if (res.success) {
          onClose()
          emits('update-list')
        }
      } catch (error) {
        // 验证失败
      }
    }
  }

  // 新商家结算价输入框输入事件
  const handleFactorySettlementPriceInput = (e: Event) => {
    checkNum(e)

    // 解决多次输入小数会保留三位的情况
    form.value.factorySettlementPrice = (e.target as HTMLInputElement).value

    // 限制金额最大只能是999999.99
    ;(e.target as HTMLInputElement).value = keepPartInteger((e.target as HTMLInputElement).value, 6)
  }

  // 新服务商结算价输入框输入事件
  const handleNetworkSettlementPriceInput = (e: Event) => {
    checkNum(e)

    // 解决多次输入小数会保留三位的情况
    form.value.networkSettlementPrice = (e.target as HTMLInputElement).value

    // 限制金额最大只能是999999.99
    ;(e.target as HTMLInputElement).value = keepPartInteger((e.target as HTMLInputElement).value, 6)
  }

  const rules = ref({
    factorySettlementPrice: [
      {
        required: true,
        message: '请填写修改商家结算',
        trigger: ['blur', 'change'],
      },
    ],
    networkSettlementPrice: [
      {
        required: true,
        message: '请填写修改服务商结算',
        trigger: ['blur', 'change'],
      },
    ],
  })

  watch(
    props,
    (value) => {
      form.value.networkSettlementPrice = value.oldNetworkSettlementPrice || '0'
      form.value.factorySettlementPrice = value.oldFactorySettlementPrice || '0'
      visible.value = value.modelValue
    },
    { immediate: true, deep: true },
  )
</script>

<template>
  <div>
    <span @click="visible = true">
      <slot></slot>
    </span>

    <HModal title="更改结算价" v-model="visible" @close="onClose" size="small">
      <el-form
        label-width="110"
        ref="formRef"
        :model="form"
        v-loading="updateLoading"
        class="modal_form_content"
        :rules="rules"
        @validate="handleFormValidate"
      >
        <!-- 商家结算 -->
        <el-form-item label="商家结算" class="form_input_item">
          <el-input disabled :value="oldFactorySettlementPrice || '0'" />
        </el-form-item>

        <!-- 修改商家结算 -->
        <el-form-item
          label="修改商家结算"
          class="form_input_item"
          :class="{ error_form_item: !formValidateResult['factorySettlementPrice'] }"
          prop="factorySettlementPrice"
        >
          <el-input
            @keyup="handleFactorySettlementPriceInput"
            placeholder="请输入修改商家结算"
            v-model="form.factorySettlementPrice"
          />
        </el-form-item>

        <!-- 服务商结算 -->
        <el-form-item label="服务商结算" disabled class="form_input_item">
          <el-input disabled :value="oldNetworkSettlementPrice || '0'" />
        </el-form-item>

        <!-- 修改服务商结算 -->
        <el-form-item label="修改服务商结算" class="form_input_item" prop="networkSettlementPrice">
          <el-input
            @keyup="handleNetworkSettlementPriceInput"
            placeholder="请输入修改服务商结算"
            v-model="form.networkSettlementPrice"
          />
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton is-modal :loading="updateLoading" @click="onSaveClick" type="primary"
          >保存</HButton
        >
        <HButton is-modal :loading="updateLoading" @click="onClose">取消</HButton>
      </template>
    </HModal>
  </div>
</template>

<style scoped lang="scss">
  @import './UpdateSettlementPrice.scss';
</style>
